package com.healthbox.appointmentservice.service.impl;

import com.healthbox.appointmentservice.DTO.AppointmentLimitDTO;
import com.healthbox.appointmentservice.DVO.AppointmentLimitDVO;
import com.healthbox.appointmentservice.entity.AppointmentLimit;
import com.healthbox.appointmentservice.entity.Hospital;
import com.healthbox.appointmentservice.mapper.AppointmentLimitMapper;
import com.healthbox.appointmentservice.mapper.HospitalMapper;
import com.healthbox.appointmentservice.service.AppointmentLimitModifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author pengpeng
 * @date 2022/5/12
 */
@Service
@Slf4j
public class AppointmentLimitModifyImpl implements AppointmentLimitModifyService {
    @Autowired
    private AppointmentLimitMapper limitRepo;
    @Autowired
    private HospitalMapper hospitalRepo;

    @Override
    public AppointmentLimitDVO newAppointmentLimit(AppointmentLimitDTO appointmentLimitDTO) {
        Hospital hospital = hospitalRepo.findOneByHospitalId(appointmentLimitDTO.getHospitalId());
        if (hospital == null) return null;
        AppointmentLimit appointmentLimit = AppointmentLimitDTO.toEntity(appointmentLimitDTO, hospital);
        limitRepo.save(appointmentLimit);
        if (appointmentLimit.getALId() == null) return null;
        return AppointmentLimitDVO.fromEntity(appointmentLimit, 0);
    }

    @Override
    public Boolean deleteAppointmentLimit(String userPhone, Long appointLimitId) {
        Integer exists = limitRepo.exists(userPhone, appointLimitId);
        if (exists==null) {
            log.warn("尝试删除一个不属于自己或不存在的记录：userPhone" + userPhone + " aLId" + appointLimitId);
            return false;
        }
        int i = limitRepo.numberOfAppointment(appointLimitId);
        if (i>0) {
            log.warn("尝试删除一个已有预约的检测时间段, aLId=" + appointLimitId);
            return false;
        }
        int delete = limitRepo.delete(appointLimitId);
        return delete==1;
    }

    @Override
    public AppointmentLimitDVO updateAppointmentLimit(AppointmentLimitDTO appointmentLimitDTO) {
        int i = limitRepo.numberOfAppointment(appointmentLimitDTO.getHospitalId());
        if (i>0) return null;
        Hospital hospital = hospitalRepo.findOneByHospitalId(appointmentLimitDTO.getHospitalId());
        if (hospital == null) return null;
        AppointmentLimit appointmentLimit = AppointmentLimitDTO.toEntity(appointmentLimitDTO, hospital);
        int update = limitRepo.update(appointmentLimit);
        return update==1? AppointmentLimitDVO.fromEntity(appointmentLimit, 0) : null;
    }
}
